package com.net.shop.car.manager.api.volley;

import java.io.UnsupportedEncodingException;

import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;

/**
 * @author Deve xu
 * 
 */
public class VolleyRequest extends StringRequest {

	private VolleyListener volleyListener;

	public VolleyRequest(int method, String url, final VolleyListener listener) {
		super(method, url, new Listener<String>() {
			@Override
			public void onResponse(String response) {
				if (listener != null) {
					listener.onResponse(); 
				}
			}
		}, new ErrorListener() {
			@Override	
			public void onErrorResponse(VolleyError error) {
				if (listener != null) {
					listener.onError(error);
				}
			}
		});

		volleyListener = listener;
	}

	@Override
	protected Response<String> parseNetworkResponse(NetworkResponse response) {
		String newStr;
		try {
			newStr = new String(response.data, "utf-8");
			System.out.println(newStr);
		} catch (UnsupportedEncodingException e) {
			newStr = new String(response.data);
		}
		if (volleyListener != null) {
			volleyListener.onParse(newStr);
		}
		return Response.success(newStr, HttpHeaderParser.parseCacheHeaders(response));
	}

}
